package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.param.UserParam;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.api.feign.system.dto.SysUserDTO;
import com.meteor.convert.InvitationConvert;
import com.meteor.convert.MalfunctionConvert;
import com.meteor.entity.Invitation;
import com.meteor.entity.Malfunction;
import com.meteor.entity.Publicity;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.InvitationMapper;
import com.meteor.mapper.MalfunctionMapper;
import com.meteor.query.InvitationQuery;
import com.meteor.query.MalfunctionQuery;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.query.PublicityQuery;
import com.meteor.service.CommunityService;
import com.meteor.service.InvitationService;
import com.meteor.service.MalfunctionService;
import com.meteor.vo.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class InvitationServiceImpl extends BaseServiceImpl<InvitationMapper, Invitation> implements InvitationService {

    private final SystemFeign systemFeign;

    private final CommunityService communityService;

    @Override
    public void save(InvitationVO vo) {
        Invitation  entity= InvitationConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

            /*if(ObjectUtils.isEmpty(vo.getCommunityId())){
                OrgAndCommunityQuery query = new OrgAndCommunityQuery();
                query.setOrgId(vo.getOrgId());
                List<CommunityVO> communityVOS = communityService.orgCommunity(query);
                if(ObjectUtils.isEmpty(communityVOS)){
                    throw new ServerException("该机构下没有小区");
                }
                entity.setCommunityId(communityVOS.get(0).getId());
            }*/

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

        if(!ObjectUtils.isEmpty(vo.getImagesUrl())){
            entity.setUrl(JSON.toJSONString(vo.getImagesUrl()));
        }

        entity.setAuditStatus(0);


//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(InvitationVO vo) {
        Invitation invitation = InvitationConvert.INSTANCE.convert(vo);
        if (ObjectUtils.isEmpty(invitation.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        if(!ObjectUtils.isEmpty(vo.getImagesUrl())){
            invitation.setUrl(JSON.toJSONString(vo.getImagesUrl()));
        }
        baseMapper.updateById(invitation);

    }

    @Override
    public InvitationVO getInvitation(String id) {
        InvitationVO invitationVO = new InvitationVO();
        invitationVO = baseMapper.getById(id);
        if(!ObjectUtils.isEmpty(invitationVO.getUrl())){
            invitationVO.setImagesUrl(JSON.parseArray(invitationVO.getUrl(), String.class));
            List<String> urls = JSON.parseArray(invitationVO.getUrl(), String.class);
            List<ImagesVO> imagesVOS = new ArrayList<>();
            urls.forEach(t->{
                ImagesVO imagesVO = new ImagesVO();
                imagesVO.setUrl(t);
                imagesVO.setName(t.substring(t.lastIndexOf("/")+1));
                imagesVOS.add(imagesVO);
            });
            invitationVO.setImages(imagesVOS);
        }
        return invitationVO;
    }

    @Override
    public List<InvitationVO> getInvitationVOList(InvitationQuery query) {
        List<Invitation> complaints = baseMapper.selectList(getWrapper(query));

        return InvitationConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<InvitationVO> pageInvitationVO(InvitationQuery query) {


        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Invitation> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<InvitationVO> list = baseMapper.getList(params);

        list.forEach(t->{
            if(!ObjectUtils.isEmpty(t.getUrl())){
                t.setImagesUrl(JSON.parseArray(t.getUrl(), String.class));
            }

        });

        return new PageResult<>(list, page.getTotal());


//        IPage<Malfunction> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<MalfunctionVO>(MalfunctionConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());

    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public PageResult<InvitationVO> miniPage(InvitationQuery query) {
        Map<String, Object> params = getNoAuthParams(query);


        // 分页查询
        IPage<Invitation> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<InvitationVO> list = baseMapper.getList(params);
        if(!ObjectUtils.isEmpty(list)){
            list.stream().forEach(t->{
                t.setImagesUrl(JSON.parseArray(t.getUrl(), String.class));
                List<String> urls = JSON.parseArray(t.getUrl(), String.class);
                List<ImagesVO> imagesVOS = new ArrayList<>();
                urls.forEach(o->{
                    ImagesVO imagesVO = new ImagesVO();
                    imagesVO.setUrl(o);
                    imagesVO.setName(o.substring(o.lastIndexOf("/")+1));
                    imagesVOS.add(imagesVO);
                });
                t.setImages(imagesVOS);
            });
        }

        return new PageResult<>(list, page.getTotal());
    }


    private Map<String, Object> getParams(InvitationQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_invitation"));

        return params;
    }

    private Map<String, Object> getNoAuthParams(InvitationQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());
        params.put("orgId", query.getOrgId());
        params.put("communityId", query.getCommunityId());
        params.put("userId", query.getUserId());
        if(ObjectUtils.isEmpty(query.getUserId())) {
            params.put("auditStatus", 1);
        }
        if(query.getPublicStatus()!=null){
            params.put("publicStatus", 1);
        }


        return params;
    }

    private Wrapper<Invitation> getWrapper(InvitationQuery query){
        LambdaQueryWrapper<Invitation> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getContent()), Invitation::getContent, query.getContent());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }

}
